package com.lujianfei.recyclerview.recyclerview_vertical;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lujianfei.recyclerview.R;
import com.lujianfei.recyclerview.adapter.RecyclerLoadMoreAdapter;
import com.lujianfei.recyclerview.entity.ListItem;
import com.lujianfei.recyclerview.widget.CustomRecyclerView;
import com.lujianfei.recyclerview.widget.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

public class LoadMoreActivity extends AppCompatActivity {

    private final static String TAG = "LoadMoreActivity";
    private final int pagesize = 20;
    private int page = 0;
    private boolean mLoadingMore;
    CustomRecyclerView recyclerview;
    RecyclerLoadMoreAdapter mRecyclerAdapter;
    Handler mHandler = new Handler();
    List<ListItem> listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view_loadmore);
        recyclerview = findViewById(R.id.recyclerview);
        recyclerview.setOnItemLongClickListener(new CustomRecyclerView.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view) {
                recyclerview.setDisableMove(true);
            }
        });
        /** 设置列表布局方式 */
        LinearLayoutManager layoutManager= new LinearLayoutManager(this);
        recyclerview.setLayoutManager(layoutManager);
        listItems = genData();
        mRecyclerAdapter = new RecyclerLoadMoreAdapter(listItems);
        mRecyclerAdapter.setHasMore(true);
        recyclerview.setAdapter(mRecyclerAdapter);

        recyclerview.addOnScrollListener(new OnLoadMoreListener(){
            @Override
            public void onLoadMore() {
                if (mLoadingMore) {
                    return;
                }
                Log.d(TAG, "onLoadMore");
                mLoadingMore = true;
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mLoadingMore = false;
                        ++ page;
                        listItems.addAll(genData());
                        mRecyclerAdapter.notifyDataSetChanged();
                    }
                },2000);
            }
        });
    }

    private List<ListItem> genData() {
        List<ListItem> listItems = new ArrayList<>();
        for (int i = page * pagesize; i < page * pagesize + pagesize; i++) {
            listItems.add(new ListItem("Title "+i,"Summary "+i));
        }
        return listItems;
    }

}
